/**
 * 加密一个字符串，基于base64编码。
 */
const encode = (text: string) => {
  const time = new Date();
  const h = time.getHours();
  const s = time.getSeconds() % 10;
  const prefix = String.fromCharCode(97 + h);
  // 在base64基础上，额外附加字符进行混淆，以实现自定义加密。
  return prefix + btoa(text) + s;
};

/**
 * 解密一个字符串，掐头去尾取中间。
 */
const decode = (text: string) => {
  const body = text.substring(1, text.length - 1);
  return atob(body);
};

export { encode, decode };

// 已弃用
const encode0 = (text: string, callback: (newText: string) => void) => {
  const blob = new Blob([text], { type: "text/plain" });
  const reader = new FileReader();
  reader.onload = () => {
    const time = new Date();
    const h = time.getHours();
    const s = time.getSeconds() % 10;
    const prefix = String.fromCharCode(97 + h);
    let newText = reader.result as string;
    newText = newText.split(",")[1];
    callback(prefix + newText + s);
  };
  reader.readAsDataURL(blob);
};
